package top.leyi.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.leyi.entity.user.User;
import top.leyi.exception.NoSuchAuthException;
import top.leyi.exception.NotSuchUserIdException;
import top.leyi.mapper.UserMapper;

import java.util.List;

/**
 * @desc 使用aop为说说进行权限认证，
 * 1 ： 用户是否存在
 * 2 ： 用户是否具有以下权限
 *
 *     超级用户   id：19  token：4ce2655b261752c951b34429073547a8
 */
@Component
@Aspect
public class AuthAop {

    @Autowired
    UserMapper userMapper;

    /**
     * @desc 对于含义参数为user的方法进行拦截
     */
     @Pointcut(value =  "execution(public * top.leyi.IService.ITalkService.*(.., top.leyi.entity.user.User))) || " +
                        "execution(public * top.leyi.IService.IActivityService.*(.., top.leyi.entity.user.User))) || ")
     public void welog(){
     }

    @Around("welog()")
    public Object   doAround(ProceedingJoinPoint jp) throws  NoSuchAuthException, Throwable{

        Object o = null;
        String[] signatures = jp.getSignature().toString().split("\\.");
        String operation = signatures[signatures.length - 1].split("\\(")[0];

        User user = (User) jp.getArgs()[1];

        user = userMapper.queryOneUserWithToken(user);
        /*
            如果没有这个用户，则抛出异常
         */
        if(user == null){
            throw new NotSuchUserIdException();
        }
        List<String> powers = userMapper.queryOwnPrivilege(user);
        boolean flag = false;
        for(String power: powers){
            if(power.equals(operation)){
                flag = true;
            }
        }
        if(!flag) {
            //throw new NoSuchAuthException("缺乏权限");
        }
        return jp.proceed(new Object[]{jp.getArgs()[0], user});
    }


}
